/**
 * 标题栏配置构建器
 * 提供链式调用的方式快速构建标题栏配置
 */

interface CustomButton {
  id: string
  icon?: string
  text?: string
  tooltip?: string
  onClick: () => void
  disabled?: boolean
  visible?: boolean
  className?: string
}

interface TitleBarConfig {
  title?: string
  showTitle?: boolean
  showIcon?: boolean
  iconSrc?: string
  showControls?: boolean
  customButtons?: CustomButton[]
  height?: string
  backgroundColor?: string
  textColor?: string
  enableDoubleClickMaximize?: boolean
}

/**
 * 预定义主题
 */
export const TITLE_BAR_THEMES = {
  dark: {
    backgroundColor: '#2c2c2c',
    textColor: '#ffffff',
    height: '32px'
  },
  light: {
    backgroundColor: '#f5f5f5',
    textColor: '#333333',
    height: '32px'
  },
  primary: {
    backgroundColor: '#1890ff',
    textColor: '#ffffff',
    height: '32px'
  },
  success: {
    backgroundColor: '#52c41a',
    textColor: '#ffffff',
    height: '32px'
  },
  warning: {
    backgroundColor: '#faad14',
    textColor: '#ffffff',
    height: '32px'
  },
  danger: {
    backgroundColor: '#ff4d4f',
    textColor: '#ffffff',
    height: '32px'
  },
  minimal: {
    backgroundColor: '#ffffff',
    textColor: '#000000',
    height: '28px'
  }
} as const

/**
 * 常用按钮图标
 */
export const BUTTON_ICONS = {
  settings: '⚙️',
  help: '❓',
  refresh: '🔄',
  search: '🔍',
  menu: '☰',
  close: '✕',
  minimize: '−',
  maximize: '□',
  restore: '❐',
  connect: '🔗',
  disconnect: '🔌',
  save: '💾',
  edit: '✏️',
  delete: '🗑️',
  add: '➕',
  remove: '➖',
  info: 'ℹ️',
  warning: '⚠️',
  error: '❌',
  success: '✅'
} as const

/**
 * 标题栏配置构建器类
 */
export class TitleBarConfigBuilder {
  private config: TitleBarConfig = {}

  /**
   * 设置标题
   */
  title(title: string): this {
    this.config.title = title
    return this
  }

  /**
   * 设置是否显示标题
   */
  showTitle(show: boolean = true): this {
    this.config.showTitle = show
    return this
  }

  /**
   * 设置是否显示图标
   */
  showIcon(show: boolean = true): this {
    this.config.showIcon = show
    return this
  }

  /**
   * 设置图标路径
   */
  iconSrc(src: string): this {
    this.config.iconSrc = src
    return this
  }

  /**
   * 设置是否显示控制按钮
   */
  showControls(show: boolean = true): this {
    this.config.showControls = show
    return this
  }

  /**
   * 设置高度
   */
  height(height: string): this {
    this.config.height = height
    return this
  }

  /**
   * 设置背景颜色
   */
  backgroundColor(color: string): this {
    this.config.backgroundColor = color
    return this
  }

  /**
   * 设置文字颜色
   */
  textColor(color: string): this {
    this.config.textColor = color
    return this
  }

  /**
   * 应用预定义主题
   */
  theme(themeName: keyof typeof TITLE_BAR_THEMES): this {
    const theme = TITLE_BAR_THEMES[themeName]
    if (theme) {
      this.config.backgroundColor = theme.backgroundColor
      this.config.textColor = theme.textColor
      this.config.height = theme.height
    }
    return this
  }

  /**
   * 设置是否启用双击最大化
   */
  enableDoubleClickMaximize(enable: boolean = true): this {
    this.config.enableDoubleClickMaximize = enable
    return this
  }

  /**
   * 添加自定义按钮
   */
  addButton(button: CustomButton): this {
    if (!this.config.customButtons) {
      this.config.customButtons = []
    }
    this.config.customButtons.push(button)
    return this
  }

  /**
   * 添加多个自定义按钮
   */
  addButtons(buttons: CustomButton[]): this {
    if (!this.config.customButtons) {
      this.config.customButtons = []
    }
    this.config.customButtons.push(...buttons)
    return this
  }

  /**
   * 快速添加设置按钮
   */
  addSettingsButton(onClick: () => void, tooltip: string = '设置'): this {
    return this.addButton({
      id: 'settings',
      icon: BUTTON_ICONS.settings,
      tooltip,
      onClick
    })
  }

  /**
   * 快速添加帮助按钮
   */
  addHelpButton(onClick: () => void, tooltip: string = '帮助'): this {
    return this.addButton({
      id: 'help',
      icon: BUTTON_ICONS.help,
      tooltip,
      onClick
    })
  }

  /**
   * 快速添加刷新按钮
   */
  addRefreshButton(onClick: () => void, tooltip: string = '刷新'): this {
    return this.addButton({
      id: 'refresh',
      icon: BUTTON_ICONS.refresh,
      tooltip,
      onClick
    })
  }

  /**
   * 快速添加菜单按钮
   */
  addMenuButton(onClick: () => void, tooltip: string = '菜单'): this {
    return this.addButton({
      id: 'menu',
      icon: BUTTON_ICONS.menu,
      tooltip,
      onClick
    })
  }

  /**
   * 构建配置对象
   */
  build(): TitleBarConfig {
    return { ...this.config }
  }

  /**
   * 重置配置
   */
  reset(): this {
    this.config = {}
    return this
  }

  /**
   * 克隆当前构建器
   */
  clone(): TitleBarConfigBuilder {
    const builder = new TitleBarConfigBuilder()
    builder.config = { ...this.config }
    if (this.config.customButtons) {
      builder.config.customButtons = [...this.config.customButtons]
    }
    return builder
  }
}

/**
 * 创建标题栏配置构建器
 */
export function createTitleBarConfig(): TitleBarConfigBuilder {
  return new TitleBarConfigBuilder()
}

/**
 * 快速创建基础配置
 */
export function createBasicConfig(title: string): TitleBarConfig {
  return createTitleBarConfig()
    .title(title)
    .theme('dark')
    .build()
}

/**
 * 快速创建带按钮的配置
 */
export function createConfigWithButtons(
  title: string,
  buttons: CustomButton[]
): TitleBarConfig {
  return createTitleBarConfig()
    .title(title)
    .theme('dark')
    .addButtons(buttons)
    .build()
}

/**
 * 快速创建最小化配置
 */
export function createMinimalConfig(title: string): TitleBarConfig {
  return createTitleBarConfig()
    .title(title)
    .theme('minimal')
    .showIcon(false)
    .showControls(false)
    .height('28px')
    .build()
}

/**
 * 快速创建交易面板配置
 */
export function createTradingPanelConfig(
  title: string,
  onSettings: () => void,
  onRefresh: () => void
): TitleBarConfig {
  return createTitleBarConfig()
    .title(title)
    .theme('dark')
    .addSettingsButton(onSettings)
    .addRefreshButton(onRefresh)
    .build()
}

/**
 * 配置验证器
 */
export function validateConfig(config: TitleBarConfig): {
  isValid: boolean
  errors: string[]
} {
  const errors: string[] = []

  if (config.title && typeof config.title !== 'string') {
    errors.push('title 必须是字符串类型')
  }

  if (config.height && !/^\d+px$/.test(config.height)) {
    errors.push('height 必须是有效的像素值，如 "32px"')
  }

  if (config.backgroundColor && !/^#[0-9A-Fa-f]{6}$/.test(config.backgroundColor)) {
    errors.push('backgroundColor 必须是有效的十六进制颜色值')
  }

  if (config.textColor && !/^#[0-9A-Fa-f]{6}$/.test(config.textColor)) {
    errors.push('textColor 必须是有效的十六进制颜色值')
  }

  if (config.customButtons) {
    config.customButtons.forEach((button, index) => {
      if (!button.id) {
        errors.push(`自定义按钮 ${index} 缺少 id 属性`)
      }
      if (!button.onClick || typeof button.onClick !== 'function') {
        errors.push(`自定义按钮 ${index} 缺少有效的 onClick 函数`)
      }
    })
  }

  return {
    isValid: errors.length === 0,
    errors
  }
}

/**
 * 配置预设
 */
export const CONFIG_PRESETS = {
  /**
   * 默认配置
   */
  default: createBasicConfig('Tauri App'),

  /**
   * 交易应用配置
   */
  trading: createTitleBarConfig()
    .title('交易终端')
    .theme('dark')
    .addButton({
      id: 'connect',
      icon: BUTTON_ICONS.connect,
      tooltip: '连接状态',
      onClick: () => console.log('切换连接')
    })
    .addSettingsButton(() => console.log('设置'))
    .build(),

  /**
   * 数据面板配置
   */
  dataPanel: createTitleBarConfig()
    .title('数据面板')
    .theme('primary')
    .addRefreshButton(() => console.log('刷新数据'))
    .addButton({
      id: 'export',
      icon: '📊',
      tooltip: '导出数据',
      onClick: () => console.log('导出')
    })
    .build(),

  /**
   * 最小化配置
   */
  minimal: createMinimalConfig('简洁模式')
}
